package com.example.demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.plaf.TextUI;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;

@WebServlet("/insertUser")
public class InsertUser extends HttpServlet {


    private Connection connection = null;
    private String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    private String JDBC_URL = "jdbc:mysql://localhost:3306/user?useSSL=false";
    private String user = "root";
    private String pass = "123456";
    private Statement statement = null;


    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");

        PrintWriter writer = resp.getWriter();
        Enumeration params = req.getParameterNames();
        String name;
        String token;

        if (params.hasMoreElements()) {
            ArrayList<String> list = Collections.list(params);

            if (list.contains("name") && list.contains("token")) {
                name = req.getParameter("name");
                token = req.getParameter("token");

                String result = insertUser(name, token);

                if (result.equals("1")) {
                    writer.println("INSERT SUCCESS");
                } else {
                    writer.println("INSERT FAILED " + result);
                }

            } else {
                writer.println("---error---");
                resp.setStatus(404);
            }

        } else {
            writer.println("---error---");
        }


    }

    private String insertUser(String namePara, String tokenPara) {
        try {
            Class.forName(JDBC_DRIVER);
            connection = DriverManager.getConnection(JDBC_URL, user, pass);
            statement = connection.createStatement();
            String sql = "INSERT INTO users (name,token) VALUES (" + namePara + "," + tokenPara + ")";
            int rs = statement.executeUpdate(sql);
            System.out.println("INSERT  " + rs);
            return rs + "";
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return e.toString();
        }
    }

}
